import { createRouter, createWebHistory } from 'vue-router'
import EventBus from '@/utils/EventBus'
import metaObj from '@/config/RouterMeta'
import { nextTick } from 'vue'

const router = createRouter({
  history: createWebHistory('/ai_closet'),
  routes: [
    {
      path: '/',
      redirect: '/Login'
    },
    {
      path: '/Login',
      name: 'Login',
      component: () => import('@/views/Login.vue')
    },
    {
      path: '/Layout',
      name: 'Layout',
      component: () => import('@/Layout/Layout.vue'),
      children: []
    }
  ]
})


const modules = import.meta.glob('/src/views/**')
for (const key in modules) {
  const name = key.slice(key.lastIndexOf('/') + 1, key.lastIndexOf('.'))
  if (name != 'Echarts' && name != 'Login') {
    router.addRoute('Layout', {
      path: `/${name}`,
      name: name,
      meta: metaObj[name as keyof typeof metaObj],
      component: modules[key]
    })
  }
}


router.beforeEach(async (to, from, next) => {
  await nextTick()
  if (sessionStorage.length == 0) {
    console.log('emit pageChange');

    EventBus.emit('PageChange', 'Login')
  } else {
    next()
  }
})



// console.log(router.getRoutes());
// EventBus.on('LoginSuccess', (department: string) => {
//   if (department !== '检验科') {
//     router.removeRoute('User');
//     console.log(router.getRoutes());
//   }
// })




EventBus.on('CodeError', (code: number) => {
  console.log('codeError');

  if (code != -1 && code != 0 && code != 200 && code != 400) {
    router.push(`/Login`);
    EventBus.emit('ResetStore')
  }
})
EventBus.on('PageChange', (name: string) => {
  console.log('pageChange');

  router.push(`/${name}`)
  if (name == 'Login') {
    EventBus.emit('ResetStore')
  }
})


export default router
